<template>
  <m-modal
    visible
    mask
    resizable
    title="设置日期和时间"
    :show-footer="true"
    cancel-text="取 消"
    ok-text="确 定"
    class="v-time-point-modal"
    :height="500"
    :width="700"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="g-fd-c g-pd-20">
      <div class="g-flex">
        <div style="align-self: center">选择时间线：</div>
        <m-dropdown class="g-flex-1">
          <div
            class="g-flex g-pd-4"
            style="border: 1px solid #d0d0d0"
          >
            <div><img :src="selectedTimeline.icon" /></div>
            <div class="g-flex-1">{{ selectedTimeline.name }}</div>
            <div><img src="statics/header/icontriangle.svg" /></div>
          </div>
          <template #dropdown>
            <m-dropdown-menu-item
              v-for="item in timelines"
              :key="item.instanceId"
              @click="() => (selectedTimeline = item)"
            >
              {{ item.name }}
            </m-dropdown-menu-item>
          </template>
        </m-dropdown>
      </div>
      <div class="g-flex">
        <div>
          <el-calendar
            ref="calendar"
            v-model="date"
          >
            <template #header="{ date }">
              <el-button
                size="small"
                @click="selectDate('prev-year')"
              >
                &lt;&lt;
              </el-button>
              <el-button
                size="small"
                @click="selectDate('prev-month')"
              >
                &lt;
              </el-button>
              <span>{{ date }}</span>
              <el-button
                size="small"
                @click="selectDate('today')"
              >
                今天
              </el-button>
              <el-button
                size="small"
                @click="selectDate('next-month')"
              >
                &gt;
              </el-button>
              <el-button
                size="small"
                @click="selectDate('next-year')"
              >
                &gt;&gt;
              </el-button>
            </template>
          </el-calendar>
        </div>
        <div style="align-self: center">
          <div class="g-m-b-10">时间日期</div>
          <el-input
            v-model="datetime"
            readonly
          ></el-input>
          <div class="g-m-tb-10">时间日期格式</div>
          <m-dropdown>
            <div
              class="g-flex g-pd-4"
              style="border: 1px solid #d0d0d0"
            >
              <div class="g-flex-1">{{ datetimeFormat }}</div>
              <div><img src="statics/header/icontriangle.svg" /></div>
            </div>
            <template #dropdown>
              <m-dropdown-menu-item
                v-for="format in datetimeFormatList"
                :key="format"
                @click="datetimeFormat = format"
              >
                {{ format }}
              </m-dropdown-menu-item>
            </template>
          </m-dropdown>
          <div class="g-m-tb-10">选择时间</div>
          <el-time-picker v-model="time"></el-time-picker>
        </div>
      </div>
    </div>
  </m-modal>
</template>

<script lang="ts">
import { mixPopup } from "@/common/Portal";
import { MetaclassType } from "@/constants/MetaclassType";
import { modelService } from "@/modules/model/service";
import dayjs from "dayjs";
import { defineComponent, PropType } from "vue";
import { PropertyRow } from "../../types";
import { PropertyDataType } from "@/constants/Enums";

const comp = defineComponent({
  name: "time-point-modal",
  props: {
    datetimeModelId: {
      type: String,
      required: true
    },
    projectId: {
      type: String,
      required: true
    },
    row: {
      type: Object as PropType<PropertyRow>,
      required: true
    },
    timelines: {
      type: Array as PropType<{ icon: string; instanceId: string; name: string; isUserCreate: boolean }[]>,
      required: true
    }
  },
  emits: ["sure", "close"],
  data() {
    return {
      datetimeFormatList: ["YYYY", "YYYY-MM", "YYYY-MM-DD", "YYYY-MM-DD HH:mm:ss"],
      datetimeFormat: "YYYY-MM-DD HH:mm:ss",
      datetime: "",
      date: undefined as Date | undefined,
      time: undefined as Date | undefined,
      timelineTypeId: "16371555332288",
      selectedTimeline: this.timelines[0]
    };
  },
  watch: {
    datetimeFormat() {
      this.formatDatetime();
    },
    date() {
      this.formatDatetime();
    },
    time() {
      this.formatDatetime();
    }
  },
  mounted() {
    const propertyDatetime = (this.row.valueSpecificationInfo?.value as string) || "";
    if (propertyDatetime) {
      this.date = dayjs(propertyDatetime).toDate();
      this.time = dayjs(propertyDatetime).toDate();
    } else {
      this.date = new Date();
      this.time = new Date();
    }
  },
  methods: {
    async handleOk() {
      let datetimeModelId = this.datetimeModelId;
      // 如果不设置时间，删除时间模型
      if (!this.datetime) {
        if (this.datetimeModelId) await modelService.removeModel(this.projectId, [this.datetimeModelId]);
        return;
      }
      /**
       * - 如果没有时间模型
       *   - 创建时间模型（在用户选择的时间线模型下创建，如果项目中没有时间线，提示用户创建）
       *   - 设置当前模型属性值
       */
      if (!datetimeModelId) {
        const date = await modelService.addModel(this.projectId, this.selectedTimeline.instanceId, MetaclassType.LiteralString, [
          "UAF::Architecture Management::Taxonomy::ISO8601DateTime"
        ]);
        if (date.length) {
          datetimeModelId = date[0].id;
          // 更新当前属性引用了时间模型的属性值
          await modelService.updateModelProperty({
            projectId: this.projectId,
            key: this.row.key,
            value: datetimeModelId,
            dataType: PropertyDataType.INSTANCE,
            instanceId: this.row.modelId,
            isMultiplicity: false
          });
        } else throw new Error("时间模型创建失败！");
      }
      // 更新时间模型值
      await modelService.updateModelProperty({
        projectId: this.projectId,
        key: "LiteralString-value",
        value: this.datetime,
        dataType: PropertyDataType.STRING,
        instanceId: datetimeModelId,
        isMultiplicity: false
      });
      this.$emit("sure");
    },
    handleCancel() {
      this.$emit("close");
    },
    selectDate(val: string) {
      (this.$refs.calendar as { selectDate: (val: string) => void }).selectDate(val);
    },
    formatDatetime() {
      const midDate = dayjs(this.date).format("YYYY-MM-DD");
      const midTime = dayjs(this.time).format("HH:mm:ss");
      this.datetime = dayjs(midDate + midTime).format(this.datetimeFormat);
    }
  }
});

mixPopup(comp);
export default comp;
</script>

<style lang="scss" scoped>
.v-time-point-modal {
  :deep(.el-calendar) {
    --el-calendar-cell-width: 45px;
  }
}
</style>
